<?php
declare (strict_types=1);

namespace app\controller;

use app\BaseController;
use app\traits\JsonResponse;
use app\model\Topic as TopicModel;

class Favorite extends BaseController {
    use JsonResponse;
    protected $middleware = [
        'auth_jwt' => ['only' => ['toggle']],
    ];
    public function toggle($topic_id){
        $topic = TopicModel::findOrEmpty($topic_id);
        if(!$topic->isEmpty()){
            $authUser = $this->auth_user;
            $res = $authUser->userTopics()->where('topic.id',$topic_id)->findOrEmpty();
            if($res->isEmpty()){
                $authUser->userTopics()->attach($topic_id,['create_time'=>time(),'update_time'=>time()]);
                $total = $authUser->userTopics()->count();
                return $this->jsonSuccess([
                    'total'=>$total,
                    'is_favorite'=>true
                ]);
            }else{
                $authUser->userTopics()->detach($topic_id);
                $total = $authUser->userTopics()->count();
                return $this->jsonSuccess([
                    'total'=>$total,
                    'is_favorite'=>false
                ]);
            }
        }else{
            return $this->jsonFail();
        }
    }
}
